import { Suspense } from "react";
import { routes } from "./routes";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { RouteRawState } from "../types";
import BeforeEachRoute from "./beforeEachRoute";
import { useSelector } from "react-redux";
import { RootState } from "../store";
const generatorRoutes = (
  routes: RouteRawState[],
  role: string
): RouteRawState[] => {
  return routes
    .filter(v => {
      if (role === "admin") return true;
      if (!v.meta.role) return true;
      return v.meta.role.includes(role);
    })
    .reduce((p, n) => {
      return n.element
        ? p.concat(n)
        : p.concat(generatorRoutes(n.children as RouteRawState[], role));
    }, [] as RouteRawState[]);
};
const Index = () => {
  const role = useSelector((state: RootState) => state.user.role);
  const asyncRoutes = generatorRoutes(routes, role);
  return (
    <BrowserRouter>
      <Suspense>
        <Routes>
          {asyncRoutes.map((v, i) => {
            return (
              <Route
                path={v.path}
                element={<BeforeEachRoute route={v}></BeforeEachRoute>}
                key={i}
              ></Route>
            );
          })}
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
};
export default Index;